package com.xlongwei.todays.config;


import java.util.List;
import javax.sql.DataSource;
import org.h2.tools.Server;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.sql.SqlUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@Condition(onClass = Server.class)
public class H2Config {
    @Inject
    SqlUtils sqlUtils;

    @Init
    public void init() throws Exception {
        log.info("init h2 connection web={} tcp={}", Solon.cfg().get("h2.console.web"),
                Solon.cfg().get("h2.console.tcp"));
        List<DataSource> dsList = Solon.context().getBeansOfType(DataSource.class);
        for (DataSource ds : dsList) {
            SqlUtils.of(ds).sql("select 1").queryValue();
        }
    }

    @Bean(destroyMethod = "shutdown")
    @Condition(onProperty = "${h2.console.web}==true")
    public Server webServer() throws Exception {
        String baseDir = Solon.cfg().get("h2.console.baseDir"),
                port = Solon.cfg().get("h2.console.webPort");
        baseDir = Utils.isBlank(baseDir) ? "." : baseDir;
        port = Utils.isBlank(port) ? "1" + Solon.cfg().get("server.port") : port;
        log.info("h2.console.web baseDir={} port={}", baseDir, port);
        return Server.createWebServer("-baseDir", baseDir, "-ifExists", "-webAllowOthers",
                "-webDaemon", "-webPort", port).start();
    }

    @Bean(destroyMethod = "shutdown")
    @Condition(onProperty = "${h2.console.tcp}==true")
    public Server tcpServer() throws Exception {
        String baseDir = Solon.cfg().get("h2.console.baseDir"),
                port = Solon.cfg().get("h2.console.tcpPort");
        baseDir = Utils.isBlank(baseDir) ? "." : baseDir;
        port = Utils.isBlank(port) ? "2" + Solon.cfg().get("server.port") : port;
        log.info("h2.console.tcp baseDir={} port={}", baseDir, port);
        return Server.createTcpServer("-baseDir", baseDir, "-ifExists", "-tcpAllowOthers",
                "-tcpDaemon", "-tcpPort", port).start();
    }
}
